package com.xuxin.baby.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.xuxin.baby.R;
import com.xuxin.baby.adapter.SearchHistoryAdapter;
import com.xuxin.baby.adapter.SearchHotAdapter;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.KeywordsBean;
import com.xuxin.baby.contract.SearchContract;
import com.xuxin.baby.database.DBControl;
import com.xuxin.baby.popup.ConfirmPopup;
import com.xuxin.baby.presenter.SearchPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.RecycleUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.08.28 0028
 * 搜索
 */
public class SearchActivity extends BaseActivity implements SearchContract.View {
    private final SearchContract.Presenter presenter = new SearchPresenter(this);
    @BindView(R.id.search_history)
    RecyclerView search_history;
    @BindView(R.id.search_hot)
    RecyclerView search_hot;
    @BindView(R.id.search)
    EditText search;

    private SearchHistoryAdapter myAdapter;
    private SearchHotAdapter mSearchHotAdapter;
    private String tenantId;//租户id
    private String token;//授权token
    private String memberId;//用户id

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_search);
    }

    @Override
    public void initView() {
        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!StringUtils.isEmpty(textView.getText().toString())) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "搜索结果");
                        bundle.putString("keywords", textView.getText().toString());
                        ActivityUtils.startActivityForResult(bundle, SearchActivity.this, ReaderVideoSlidingActivity.class,200);
                        DBControl.insertSearch(textView.getText().toString());
                    }
                }
                return false;
            }
        });
        RecycleUtils.chips(search_history);
        myAdapter = new SearchHistoryAdapter();
        search_history.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("title", "搜索结果");
                bundle.putString("keywords", myAdapter.getData().get(position).getTitle());
                ActivityUtils.startActivity(bundle, SearchActivity.this, ReaderVideoSlidingActivity.class);
            }
        });
        RecycleUtils.init(search_hot);
        mSearchHotAdapter = new SearchHotAdapter();
        search_hot.setAdapter(mSearchHotAdapter);
        mSearchHotAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("title", "搜索结果");
                bundle.putString("keywords", mSearchHotAdapter.getData().get(position).getKeyword());
                ActivityUtils.startActivityForResult(bundle, SearchActivity.this, ReaderVideoSlidingActivity.class,200);
                DBControl.insertSearch(mSearchHotAdapter.getData().get(position).getKeyword());
            }
        });
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        memberId = aCache.getAsString(BaseConstant.memberId);
        myAdapter.setList(DBControl.querySearch());
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onComplete() {
        if (!myAdapter.getData().isEmpty()) {
            search_history.setVisibility(View.VISIBLE);
        }
    }

    @Override
    @OnClick({R.id.search_delete})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.search_delete) {
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asCustom(new ConfirmPopup(context, "确定要删除历史搜索吗？", new ConfirmPopup.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            DBControl.deleteAllSearch();
                            myAdapter.setList(null);
                        }
                    })).show();
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.getKeywords(tenantId, token, memberId);
            }
            return false;
        }
    });

    @Override
    public void onSuccess(KeywordsBean keywordsBean) {
        if (null != keywordsBean && null != keywordsBean.getResult()) {
            mSearchHotAdapter.setList(keywordsBean.getResult().getItems());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        myAdapter.setList(DBControl.querySearch());
    }
}